/**
 * ToolResultView.js
 * 
 * 负责工具执行结果面板的逻辑。
 * 展示手动调用工具的结果卡片。
 */

(function() {
    'use strict';

    class ToolResultView {
        constructor() {
            this.container = document.getElementById('tool-result-content');
            this.results = []; // 存储工具执行结果
        }

        /**
         * 添加工具执行结果
         * @param {Object} result - 工具执行结果
         */
        addResult(result) {
            if (!this.container) return;

            // 移除占位符
            const placeholder = this.container.querySelector('.placeholder-text');
            if (placeholder) {
                placeholder.remove();
            }

            // 将结果添加到数组开头（最新的在最上面）
            this.results.unshift(result);

            // 重新渲染所有结果
            this._render();
        }

        /**
         * 渲染所有结果卡片
         * @private
         */
        _render() {
            if (!this.container) return;

            this.container.innerHTML = '';

            if (this.results.length === 0) {
                this.container.innerHTML = '<p class="placeholder-text">Select a tool to view results</p>';
                return;
            }

            this.results.forEach((result, index) => {
                const card = this._createCard(result, index);
                this.container.appendChild(card);
            });
        }

        /**
         * 创建结果卡片
         * @private
         */
        _createCard(result, index) {
            const card = document.createElement('div');
            card.className = 'tool-result-card';
            card.dataset.index = index;

            const statusClass = result.success ? 'success' : 'error';
            const statusIcon = result.success ? 'check' : 'error';
            
            card.innerHTML = `
                <div class="tool-result-card-header">
                    <span class="tool-name">${result.toolName || 'Unknown Tool'}</span>
                    <span class="tool-status ${statusClass}">
                        <span class="codicon codicon-${statusIcon}"></span>
                        ${result.success ? 'Success' : 'Failed'}
                    </span>
                </div>
                <div class="tool-result-card-meta">
                    <span class="tool-time">${this._formatTime(result.timestamp)}</span>
                    ${result.duration ? `<span class="tool-duration">${result.duration}ms</span>` : ''}
                </div>
                <div class="tool-result-card-preview">
                    <pre>${this._formatPreview(result)}</pre>
                </div>
                <div class="tool-result-card-actions">
                    <vscode-button appearance="secondary" class="btn-view-detail">查看详情</vscode-button>
                </div>
            `;

            // 绑定查看详情按钮
            const detailBtn = card.querySelector('.btn-view-detail');
            if (detailBtn) {
                detailBtn.onclick = (e) => {
                    e.stopPropagation();
                    this._showDetailDialog(result);
                };
            }

            return card;
        }

        /**
         * 格式化时间
         * @private
         */
        _formatTime(timestamp) {
            if (!timestamp) return 'Unknown time';
            const date = new Date(timestamp);
            return date.toLocaleTimeString('zh-CN');
        }

        /**
         * 格式化输出
         * @private
         */
        _formatOutput(result) {
            if (result.error) {
                return result.error;
            }
            if (result.output) {
                if (typeof result.output === 'object') {
                    return JSON.stringify(result.output, null, 2);
                }
                return result.output;
            }
            return 'No output';
        }

        /**
         * 格式化预览（截断长文本）
         * @private
         */
        _formatPreview(result) {
            const full = this._formatOutput(result);
            const maxLength = 200;
            
            if (full.length <= maxLength) {
                return full;
            }
            
            return full.substring(0, maxLength) + '...\n\n(点击"查看详情"查看完整内容)';
        }

        /**
         * 显示详情对话框
         * @private
         */
        _showDetailDialog(result) {
            const statusClass = result.success ? 'success' : 'error';
            const statusIcon = result.success ? 'check' : 'error';
            const statusText = result.success ? '执行成功' : '执行失败';

            const contentHtml = `
                <div class="tool-detail-info">
                    <div class="tool-detail-row">
                        <span class="tool-detail-label">工具名称:</span>
                        <span class="tool-detail-value">${result.toolName || 'Unknown'}</span>
                    </div>
                    <div class="tool-detail-row">
                        <span class="tool-detail-label">执行状态:</span>
                        <span class="tool-status ${statusClass}">
                            <span class="codicon codicon-${statusIcon}"></span>
                            ${statusText}
                        </span>
                    </div>
                    <div class="tool-detail-row">
                        <span class="tool-detail-label">执行时间:</span>
                        <span class="tool-detail-value">${this._formatTime(result.timestamp)}</span>
                    </div>
                    ${result.duration ? `
                        <div class="tool-detail-row">
                            <span class="tool-detail-label">耗时:</span>
                            <span class="tool-detail-value">${result.duration}ms</span>
                        </div>
                    ` : ''}
                </div>
                
                <div class="tool-detail-section">
                    <h4>执行结果</h4>
                    <div class="dialog-code-block">${this._formatOutput(result)}</div>
                </div>
            `;

            const dialog = new window.DialogComponent({
                title: `工具执行详情: ${result.toolName || 'Unknown'}`,
                content: contentHtml,
                width: '800px',
                buttons: [
                    {
                        text: '关闭',
                        action: 'close'
                    }
                ]
            });

            dialog.show();
        }

        /**
         * 清空所有结果
         */
        clear() {
            this.results = [];
            this._render();
        }

        /**
         * 恢复手动工具执行历史
         * @param {Array} history - ManualToolHistoryItem 数组
         */
        restoreManualHistory(history) {
            if (!history || history.length === 0) return;

            // 清空当前结果
            this.results = [];

            // 将历史记录转换为结果格式
            history.forEach(item => {
                const result = {
                    ...item.result,
                    toolName: item.toolName,
                    timestamp: item.timestamp
                };
                this.results.push(result);
            });

            // 渲染所有结果（最新的在最上面，所以不需要反转）
            this._render();
        }
    }

    window.ToolResultView = ToolResultView;
})();